package cn.datawin.cf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
 
public class CompletableFutureTimeoutExample {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                // 模拟长时间运行的任务
                Thread.sleep(2000);
                System.out.println("异步任务完成-----");
            } catch (Exception e) {
                System.out.println("异步任务异常-----");
                Thread.currentThread().interrupt();
            }
            return "任务完成";
        });
        System.out.println(System.currentTimeMillis());
        String result = null;
        try {
            // 设置超时时间为1秒
            result = future.get(3, TimeUnit.SECONDS);
            System.out.println(System.currentTimeMillis());
            System.out.println("结果: " + result);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            System.out.println("处理超时逻辑");
            // 可以在这里执行超时后的处理逻辑
            if (e instanceof TimeoutException) {
                System.out.println("超时异常: " + e.getMessage());
            }
        } finally {
            // 取消未完成的任务
            future.cancel(true);
        }
    }
}